﻿/*
 * 漠然 @ 2013年7月16日11:36:41
 * 主界面设计 
 * 
 * 修改方案：将于游戏相关的项目进行剥离 统一交给Manger来处理
 * 
 */

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mrsoft.AutoStarter;
using Mrsoft.Common;
using Mrsoft.Core;
using Mrsoft.Model;
using Mrsoft.Properties;

namespace Mrsoft.UI
{
    public partial class FrmMain : Form
    {
        #region UI.窗口控制类交互代码
        public FrmMain() {
            InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);

            #region ICO先关加载动作
            MainPlugin.FrmSkinLoad(this, frmControl);
            frmControl.FormTitle = Text;
            this.Icon = Resources._148;
            frmControl.Icon = Resources._148;
            deskIcon.Icon = Resources._148;
            #endregion
        }

        /// <summary>
        /// 游戏实例对象管理
        /// </summary>
        private CoreManager coreManager;

        private void frmMain_Load(object sender, EventArgs e) {

            MsgListener.CommonMsgEvent += CommonMsgEvent;
            MsgListener.MsgBoxMsgEvent += MsgBoxMsgEvent;

            coreManager = new CoreManager(CoreManagerAddGame);
            coreManager.GameStateChangeNofifyEvent += LsStateChangeEvent;
            coreManager.GameQuitNotifyEvent += QuitEvent;
            coreManager.SetShowerEvent += SetShowerEvent;

            GemeShow();
            LoadDropSet();

            txtYuanBaoBiLi.Text = (1000 * YuanBaoBiLi.Value).ToString();
            AlarmMusicFile.SetBind(lbAlarmMusic, "Text", true);
            DatiManager.DatiSeviceHost.SetBind(txtSeverIP, "Text", true);
            DirectDealGame.AutoGetOutOfShengShouShanFb.SetBind(cbxpigAutoOut, "Checked", true);
            AccManager.GameDirectory.SetBind(txtGamePath, "Text", true);
            ShowList();
        }

        /// <summary>
        /// 在没有显示对象的时候
        /// 创建新的游戏监控的时候设置显示对象
        /// </summary>
        /// <param name="core"></param>
        private void SetShowerEvent(DirectDealGame core) {
            if (theShower == null) {
                theShower = core;
            }
        }

        /// <summary>
        /// 添加了新的游戏对象 请求显示
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        private void CoreManagerAddGame(string id, string name) {
            this.Invoke((MethodInvoker)delegate {
                lsGames.Items.Add(id)
                    .SubItems.AddRange(new[] { 
                       name,
                        "加载"
                    });
            });
        }

        /// <summary>
        /// 游戏退出UI资源释放处理事件
        /// </summary>
        /// <param name="dwProcessId"></param>
        private void QuitEvent(int dwProcessId) {
            DirectDealGame game;
            if (coreManager.Remove(dwProcessId, out game)) {
                //列表框显示清除
                lsGames.Invoke((MethodInvoker)delegate {
                    foreach (ListViewItem temItem in lsGames.Items) {
                        if (temItem.Text == dwProcessId.ToString()) {
                            lsGames.Items.Remove(temItem);
                            break;
                        }
                    }
                });
                //客户端退出通知
                CommonMsgEvent(string.Format("{0}的客户端程序退出了！", game.PermaName));
            }
            else {
                CommonMsgEvent(string.Format("{0}的客户端程序退出异常！", dwProcessId));
            }
        }


        /// <summary>
        /// UI线程处理 外挂角色动作状态
        /// </summary>
        /// <param name="dwProcessId"></param>
        /// <param name="stateMsg"></param>
        /// <param name="index"></param>
        private void LsStateChangeEvent(int dwProcessId, string stateMsg, int index) {
            this.Invoke((MethodInvoker)delegate {
                string str = dwProcessId.ToString();
                foreach (ListViewItem temItem in lsGames.Items) {
                    if (temItem.Text == str) {
                        if (index == 1 && theShower != null && coreManager.GetByProcessId(dwProcessId) == theShower)
                            ReLoadConfig();
                        temItem.SubItems[index].Text = stateMsg;
                    }
                }
            });
        }

        /// <summary>
        ///  UI线程的处理 消息框消息处理
        /// </summary>
        /// <param name="msgStr"></param>
        /// <param name="msgCaption"></param>
        private void MsgBoxMsgEvent(string msgStr, string msgCaption) {
            if (InvokeRequired) {
                var deMethod = new MsgListener.MsgBoxMsg(MsgBoxMsgEvent);
                Invoke(deMethod, new object[] { msgStr, msgCaption });
            }
            else {
                MessageBox.Show(this, msgStr, msgCaption);
            }
        }

        /// <summary>
        /// UI线程的处理 日志显示处理
        /// </summary>
        /// <param name="msgStr">日志消息</param>
        private void CommonMsgEvent(string msgStr) {
            if (InvokeRequired) {
                var deMethod = new MsgListener.CommonMsg(CommonMsgEvent);
                Invoke(deMethod, new object[] { msgStr });
            }
            else {
                string msg = string.Format("[{0}]{1}", DateTime.Now.ToLongTimeString(), msgStr);
                int msgIndex = lsDialog.Items.Add(msg);
                if (msgIndex > 8)
                    lsDialog.TopIndex = msgIndex - 8;
            }
        }

        /// <summary>
        /// 关闭第一次弹窗提示
        /// </summary>
        private bool mAsk = true;

        /// <summary>
        /// 用于判定关闭窗口的动作是执行最小化还是执行关闭
        /// </summary>
        private bool frmCanClosed;

        /// <summary>
        /// 窗口关闭动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ActionCloseWindow(object sender, EventArgs e) {
            if (mAsk) {
                DialogResult pdRs = MessageBox.Show(this, "您希望直接关闭软件还是最小化到托盘？\r\n是：直接关闭  否：最小化到托盘", "关闭选择", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                mAsk = false;
                if (pdRs == DialogResult.Yes)
                    frmCanClosed = true;
            }
            Close();
        }

        /// <summary>
        /// 将窗口最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ActionMinWindow(object sender, EventArgs e) {
            WindowState = FormWindowState.Minimized;
        }

        /// <summary>
        /// 程序关闭处理过程重载
        /// </summary>
        /// <param name="e"></param>
        protected override void OnFormClosing(FormClosingEventArgs e) {
            if (!frmCanClosed) {
                e.Cancel = true;
                Hide();
            }
            else {
                MsgListener.CommonMsgEvent -= CommonMsgEvent;
                MsgListener.MsgBoxMsgEvent -= MsgBoxMsgEvent;
                DirectDealGame.LsStateChangeEvent -= LsStateChangeEvent;
                DirectDealGame.QuitEvent -= QuitEvent;
                coreManager.Stop();
            }
        }

        /// <summary>
        /// 窗口菜单设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmControl_MenuBtnClick(object sender, EventArgs e) {
            var pcontrol = sender as Control;
            //显示的位置在菜单ICO图标下方
            if (pcontrol != null)
                frmControlMenu.Show(pcontrol, 0, pcontrol.Height);
        }

        /// <summary>
        /// ICO图标双击事件--显示窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deskIcon_DoubleClick(object sender, EventArgs e) {
            Show();
        }

        /// <summary>
        /// ICO图标事件--退出外挂
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmControl退出软件_Click(object sender, EventArgs e) {
            frmCanClosed = true;
            Application.Exit();
        }

        #endregion

        #region 游戏监听
        /// <summary>
        /// 软件启动时间
        /// </summary>
        private readonly DateTime _softStartTime = DateTime.Now;

        private void GemeShow() {
            new Task(GamerShowThread).Start();
        }

        /// <summary>
        /// gamer信息获取线程
        /// </summary>
        private void GamerShowThread() {
            while (!frmCanClosed) {
                Thread.Sleep(500);
                if (frmCanClosed)
                    continue;
                ShowInfo();
            }
        }

        /// <summary>
        /// gamer信息展示
        /// </summary>
        private void ShowInfo() {
            var shower = theShower;
            if (shower == null) {
                return;
            }

            if (this.InvokeRequired) {
                this.Invoke(new MethodInvoker(ShowInfo));
            }
            else {
                listenCounterShowr.Text = string.Format("启动时长: {0}", (DateTime.Now - _softStartTime).ToString(@"dd\:hh\:mm\:ss"));
                if (shower == null)
                    return;
                lbDati.Text = string.Format("答题：{0}", shower.TheGamer.DatiTime);
                lbPet.Text = string.Format("宠物：{0}", shower.TheGamer.PetName);
                lbPetHappy.Text = string.Format("快乐：{0}", shower.TheGamer.PetHappy);
                lbMap.Text = string.Format("{0}({1} , {2})", shower.TheGamer.MapName, (int)shower.TheGamer.JsXY.X, (int)shower.TheGamer.JsXY.Y);
                lbPetHp.Text = string.Format("血况：{0}/{1}", shower.TheGamer.PetHP, shower.TheGamer.PetHPMax);
                lbHp.Text = string.Format("血况：{0}/{1}", shower.TheGamer.HP, shower.TheGamer.HPMax);
                lbMp.Text = string.Format("血况：{0}/{1}", shower.TheGamer.MP, shower.TheGamer.MPMax);
                lbMonKilled.Text = string.Format("杀怪：{0}", shower.TheGamer.MonKilled);
                lbEnergy.Text = string.Format("精力：{0}/{1}", shower.TheGamer.Energy, shower.TheGamer.EnergyMax);
            }

        }
        #endregion

        #region 切换选中对象
        /// <summary>
        /// 检查当前是否选定了一个角色作为UI载体
        /// </summary>
        /// <returns></returns>
        private bool TheShowerCheck() {
            if (theShower == null) {
                MsgBoxMsgEvent("当前没有一个选中的角色哦!\r\n请用鼠标点选左边列表框中你要操作的角色！", "操作失败");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 对UI载体的游戏角色对象的引用
        /// </summary>
        DirectDealGame theShower {
            set {
                if (coreManager.Shower != value) {
                    coreManager.Shower = value;
                    ReLoadConfig();
                }
            }
            get { return coreManager.Shower; }
        }

        /// <summary>
        /// 通过角色列表选中角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lsGames_SelectedIndexChanged(object sender, EventArgs e) {
            if (lsGames.SelectedItems.Count > 0) {
                var pid = int.Parse(lsGames.SelectedItems[0].Text);
                DirectDealGame game = coreManager.GetByProcessId(pid);
                if (game != null) {
                    while (game.Conf == null || !game.Conf.IsAvalable || string.IsNullOrEmpty(game.PermaName)) {
                        MsgBoxMsgEvent("数据还在加载中……", "等待提示");
                        Thread.Sleep(100);
                        if (frmCanClosed)
                            return;
                    }
                    theShower = game;
                }
            }
        }

        /// <summary>
        /// 配置信息绑定
        /// </summary>
        private void ReLoadConfig() {
            if (this.InvokeRequired) {
                this.Invoke(new MethodInvoker(ReLoadConfig));
            }
            else {

                lbBaitanLocation.Text = theShower.BaitanConf.ShowMapAndLocation();
                ShowBaitanPriceMap();

                lbName.Text = theShower.PermaName;
                theShowerName.Text = theShower.PermaName;
                //动态标题按钮
                btnEMHealth.Text = theShower.Controler.EMControler ? "停止加血" : "开启加血";
                btnCatchFloorBag.Text = theShower.Controler.JWControler ? "停止捡物" : "开启捡物";
                btnCailiaoJiaGong.Text = theShower.Controler.JGControler ? "停止加工" : "开始加工";
                btnBunking.Text = theShower.Controler.BunkingControler ? "停止喊话" : "开始喊话";
                //挂机点
                cmbGuaJiDians.Items.Clear();
                foreach (GuaJiDian tem in theShower.KillMonData.TheDians) {
                    cmbGuaJiDians.Items.Add(tem.ToString());
                }
                cmbAnSkills.Items.Clear();
                foreach (Skill tem in theShower.KillMonData.TheSkills) {
                    cmbAnSkills.Items.Add(tem.ToString());
                }
                imageHeader.BackgroundImage = theShower.GetHeader();
                //种植配置
                cmbZzMap.Text = theShower.TheZhongZhiInfo.DefaultZhongZhiMap;
                cmbZzShuZhi.Text = theShower.TheZhongZhiInfo.DefaultZhongZhiShuZhi.ToString();
                cmbZzZuoWu.Text = theShower.TheZhongZhiInfo.DefaultZhongZhiZuoWu;
                cbxZzZhuanZhong.Checked = theShower.TheZhongZhiInfo.AutoChangetZaoToWan;
                txtZzEnergy.Text = theShower.TheZhongZhiInfo.LowestEnergy.ToString();
                //帮会信息
                //theShower.Conf.msMyBanghuiMap.SetBind(txtMyBanghuiMap, "Text");
                //保护信息
                theShower.Conf.miJsHP.SetBind(txtJsHp, "Text");
                theShower.Conf.miJsMP.SetBind(txtJsMp, "Text");
                theShower.Conf.miPetHappy.SetBind(txtPetHappy, "Text");
                theShower.Conf.miPetHP.SetBind(txtPetHp, "Text");
                theShower.Conf.mbJsHP.SetBind(cbxJsHp, "Checked");
                theShower.Conf.mbJsMP.SetBind(cbxJsMp, "Checked");
                theShower.Conf.mbPetHappy.SetBind(cbxPetHappy, "Checked");
                theShower.Conf.mbPetHP.SetBind(cbxPetHp, "Checked");
                theShower.Conf.msJsHP.SetBind(cmbJsHP, "Text");
                theShower.Conf.msJsMP.SetBind(cmbJsMp, "Text");
                theShower.Conf.msPetHP.SetBind(cmbPetHp, "Text");
                theShower.Conf.msPetHappy.SetBind(cmbPetHappy, "Text");
                //采集
                theShower.Conf.CaiJiMap.SetBind(cmbCJMap, "Text");
                theShower.Conf.CaiJiYS.SetBind(cbxCaiJiYs, "Checked");
                theShower.Conf.CaiJiMinEnergy.SetBind(txtCaiJiMinEnergy, "Text");
                theShower.Conf.CaiJiMinerals.SetBind(txtCJMinerals, "Text");
                theShower.Conf.CaiJiYuanDiRest.SetBind(cbxCaiJiYuanDiRest, "Checked");
                //峨眉加血
                theShower.Conf.EMCXYQ.SetBind(rbtnEMCXYQ, "Checked");
                theShower.Conf.EMFGPZ.SetBind(rbtnEMFGPZ, "Checked");
                theShower.Conf.EMQXPT.SetBind(rbtnEMQXPT, "Checked");
                theShower.Conf.EMCHQY.SetBind(cbxEMCHQY, "Checked");
                theShower.Conf.EMJZDJ.SetBind(cbxEMJZDJ, "Checked");
                theShower.Conf.EMHealthPercent.SetBind(cmbEMPercent, "Text");
                //捡物
                theShower.Conf.JianwuDrop.SetBind(cbxDrop, "Checked");
                theShower.Conf.JianwuCoolDown.SetBind(txtJianwuCoolDown, "Text");
                theShower.Conf.JianwuDistance.SetBind(txtJianwuDistance, "Text");
                //cpu
                theShower.Conf.CPUDownYN.SetBind(cbxCPUDown, "Checked");
                theShower.Conf.CPUDownPercent.SetBind(txtCPUDown, "Text");
                //挂机设置
                theShower.Conf.KillSkillYN.SetBind(cbxReleaseSkill, "Checked");
                theShower.Conf.KillOneByOneYN.SetBind(cbxKillOneByOne, "Checked");
                theShower.Conf.KillNotAnMode.SetBind(cbxNotAnMode, "Checked");
                theShower.Conf.KillFullHPYN.SetBind(cbxFullHP, "Checked");
                theShower.Conf.KillFullMonYN.SetBind(cbxFullMon, "Checked");
                theShower.Conf.KillFullMonCount.SetBind(cmbKillMonCount, "Text");
                theShower.Conf.KillNextTask.SetBind(cmbGuaJiContinue, "Text");
                theShower.Conf.KillAutoBackYN.SetBind(cbxKillAutoBack, "Checked");
                theShower.Conf.KillAutoBackMapName.SetBind(cmbKillBackMap, "Text");
                theShower.Conf.KillSelectKey.SetBind(cmbKillSelectKey, "Text");
                theShower.Conf.KillCommonCall.SetBind(cbxSkillCallMethod, "Checked");
                //副本设置
                theShower.Conf.HsYN.SetBind(cbxHs, "Checked");
                theShower.Conf.FzYN.SetBind(cbxFz, "Checked");
                theShower.Conf.HsMap.SetBind(cmbHsMap, "Text");
                theShower.Conf.FzMap.SetBind(cmbFzMap, "Text");
                theShower.Conf.HFCJ.SetBind(cbxHFCJ, "Checked");
                //监狱地府
                theShower.Conf.mbJail.SetBind(cbxJailYN, "Checked");
                theShower.Conf.mbHell.SetBind(cbxHellYN, "Checked");
                theShower.Conf.msHell.SetBind(cmbHellMap, "Text");
                theShower.Conf.msJail.SetBind(cmbJailMap, "Text");
                //钓鱼
                theShower.Conf.DYMap.SetBind(cmbFishMap, "Text");
                theShower.Conf.DYSellYN.SetBind(cbxFishSell, "Checked");
                theShower.Conf.BunkingConfig.SetBind(txtBunking, "Text");
                theShower.Conf.SiJueFirstAttack.SetBind(SiJueStartCache, "Checked");
                theShower.Conf.ZhongzhiContinueCaiji.SetBind(cbxZhongzhiCotinueCaiji, "Checked");
                theShower.Conf.CaiJiBaitan.SetBind(cbxCaijiBaitan, "Checked");
            }
        }
        #endregion

        #region 任务启动

        private void StartWork(ThreadMethods method) {
            if (TheShowerCheck()) {
                theShower.TaskStartManger(method);
            }
        }


        private void btnShouYB_Click(object sender, EventArgs e) {
            StartWork(ThreadMethods.收元宝);
        }

        private void StartKaiTu(object sender, EventArgs e) {
            StartWork(ThreadMethods.开图);
        }

        private void StartSiJue(object sender, EventArgs e) {
            StartWork(ThreadMethods.四绝);
        }

        private void StartCaiJi(object sender, EventArgs e) {
            StartWork(ThreadMethods.采集);
        }


        private void StartLianJin(object sender, EventArgs e) {
            StartWork(ThreadMethods.炼金);
        }

        private void StartGuaJi(object sender, EventArgs e) {
            StartWork(ThreadMethods.挂机);
        }

        private void StartXiangQi(object sender, EventArgs e) {
            StartWork(ThreadMethods.箱子棋局);
        }

        private void StartHeFan(object sender, EventArgs e) {
            StartWork(ThreadMethods.和尚反贼);
        }

        /// <summary>
        /// 开启钓鱼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDiaoYu(object sender, EventArgs e) {
            StartWork(ThreadMethods.钓鱼);
        }

        /// <summary>
        /// 开启许愿
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartXuYuan(object sender, EventArgs e) {
            StartWork(ThreadMethods.许愿);
        }

        /// <summary>
        /// 开始刷猪
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartZhu(object sender, EventArgs e) {
            StartWork(ThreadMethods.圣兽山);
        }

        /// <summary>
        /// 自动打图开启按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAutoDatuClick(object sender, EventArgs e) {
            StartWork(ThreadMethods.打图);
        }


        private void StopWorking(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                theShower.Controler.Stop();
            }
        }
        #endregion

        #region 答题相关
        int _dtPoints;
        private void btnDati_Click(object sender, EventArgs e) {
            new MethodInvoker(DatiLogin).BeginInvoke(null, null);
        }

        private void DatiLogin() {
            if (DatiManager.HuiYanDatiService == null || !DatiManager.HuiYanDatiService.IsReady) {
                MsgBoxMsgEvent("答题插件处于不可用状态", "答题错误");
                return;
            }
            this.Invoke((MethodInvoker)delegate {
                btnDati.Enabled = false;
            });
            int temDtPoints = DatiManager.HuiYanDatiService.Points;
            if (DatiManager.HuiYanDati) {
                DatiManager.HuiYanDati = false;
                CommonMsgEvent(string.Format("[答题系统]:你本次使用：{0}", _dtPoints - temDtPoints));
                this.Invoke((MethodInvoker)delegate {
                    btnDati.Text = "打开答题";
                    lbDatiRest.Text = "剩余答题：" + temDtPoints;
                });
            }
            else if (temDtPoints > 0) {
                this.Invoke((MethodInvoker)delegate {
                    lbDatiRest.Text = "自动答题中……";
                    btnDati.Text = "关闭答题";
                });
                _dtPoints = temDtPoints;
                DatiManager.HuiYanDati = true;
                CommonMsgEvent(string.Format("[答题系统]:你当前剩余：{0}", temDtPoints));
                if (temDtPoints < 50)
                    ShowDatiPage();
            }
            this.Invoke((MethodInvoker)delegate {
                btnDati.Enabled = true;
            });
        }
        #endregion

        #region 峨眉加血
        private void btnEMHealth_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                if (theShower.Controler.EMControler) {
                    theShower.Controler.EMControler = false;
                    btnEMHealth.Text = "开启加血";
                }
                else if (theShower.TheMenPai.MyMenPai == MenPaiSet.峨眉) {
                    new Task(theShower.EmHealthThread, TaskCreationOptions.LongRunning).Start();
                    btnEMHealth.Text = "停止加血";
                }
            }
        }
        #endregion

        #region 自动捡物

        /// <summary>
        /// 角色背包新物品检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBagView_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                cmbBagView.Items.Clear();
                List<GamerBag> temBags;
                var newBagWuPing = new HashSet<string>();
                theShower.ViewMyBag(out temBags, 0, 60);
                foreach (var bag in temBags.Where(tem => !DirectDealGame.DropSet.Contains(tem.Name))) {
                    if (!newBagWuPing.Contains(bag.Name)) {
                        newBagWuPing.Add(bag.Name);
                    }
                }
                cmbBagView.Items.AddRange(newBagWuPing.ToArray());
            }
        }

        private void btnAddDropset_Click(object sender, EventArgs e) {
            string name = cmbBagView.Text;
            if (!string.IsNullOrEmpty(name) && !DirectDealGame.DropSet.Contains(name)) {
                DirectDealGame.DropSet.Add(name);
                cmbDropset.Items.Add(name);
                File.AppendAllText(@".\user\过滤列表.dat", name + "\r\n", Encoding.UTF8);
            }
        }


        private void btnDropsetDeleteItem_Click(object sender, EventArgs e) {
            string name = cmbDropset.Text;
            if (!string.IsNullOrEmpty(name) && DirectDealGame.DropSet.Contains(name)) {
                DirectDealGame.DropSet.Remove(name);
                cmbDropset.Items.Remove(name);
                var sb = new StringBuilder();
                foreach (string str in DirectDealGame.DropSet) {
                    sb.AppendFormat("{0}\r\n", str);
                }
                File.WriteAllText(@".\user\过滤列表.dat", sb.ToString(), Encoding.UTF8);
            }
        }

        private void LoadDropSet() {
            if (File.Exists(@".\user\过滤列表.dat")) {
                string temStr = File.ReadAllText(@".\user\过滤列表.dat", Encoding.UTF8);
                string[] temArr = temStr.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                temArr = temArr.OrderBy(str => str).ToArray();
                foreach (string t in temArr) {
                    DirectDealGame.DropSet.Add(t);
                }
                cmbDropset.Items.AddRange(temArr);
            }
        }

        private void btnCatchFloorBag_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                if (theShower.Controler.JWControler) {
                    btnCatchFloorBag.Text = "开启捡物";
                    theShower.Controler.JWControler = false;
                }
                else {
                    btnCatchFloorBag.Text = "停止捡物";
                    new Task(theShower.JianwuThread, TaskCreationOptions.LongRunning).Start();
                }
            }
        }
        #endregion

        #region 材料加工
        private void btnCailiaoJiaGong_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                if (theShower.Controler.JGControler) {
                    theShower.Controler.JGControler = false;
                    btnCailiaoJiaGong.Text = "开始加工";
                }
                else if (!string.IsNullOrEmpty(cmbCailiaoJiaGong.Text)) {
                    CaiLiaoJiaGongType theType;
                    if (Enum.TryParse(cmbCailiaoJiaGong.Text.Trim(), out theType)) {
                        btnCailiaoJiaGong.Text = "停止加工";
                        theShower.TaskStartManger(ThreadMethods.加工, theType);
                    }
                    else
                        MsgBoxMsgEvent("请选择要加工的类型,不要手动修改列表内容", "参数错误");
                }
            }
        }
        #endregion

        #region 挂机信息
        //挂机点和技能
        private void btnAddGuaJiDian_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                var temDian = new GuaJiDian { Map = theShower.TheGamer.MapName };
                int.TryParse(txtDianCD.Text, out temDian.Cd);
                temDian.GuaJiXy = theShower.TheGamer.JsXY;
                if (!string.IsNullOrEmpty(temDian.Map) && temDian.GuaJiXy.Islegal()) {
                    if (temDian.Cd == 0)
                        temDian.Cd = 20;
                    theShower.KillMonData.TheDians.Add(temDian);
                    theShower.KillMonData.Save();
                    cmbGuaJiDians.Items.Add(temDian.ToString());
                }
            }
        }
        private void btnDeleteGuaJiDian_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                foreach (GuaJiDian temDian in theShower.KillMonData.TheDians) {
                    if (temDian.ToString() == cmbGuaJiDians.Text) {
                        theShower.KillMonData.TheDians.Remove(temDian);
                        cmbGuaJiDians.Items.Remove(cmbGuaJiDians.SelectedItem);
                        theShower.KillMonData.Save();
                        cmbGuaJiDians.Text = "";
                        break;
                    }
                }
            }
        }
        private void btnAddAnSkill_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                int id, cd;
                if (int.TryParse(txtAnSkillCD.Text.Trim(), out cd) &&
                    DmLibary.KeyDic.TryGetValue(cmbAnSkillID.Text.Trim().ToLower(), out id)) {
                    var temSkill = new Skill(true, id, cd) { Name = cmbAnSkillID.Text.Trim() };
                    theShower.KillMonData.TheSkills.Add(temSkill);
                    cmbAnSkills.Items.Add(temSkill.ToString());
                    theShower.KillMonData.Save();
                }
            }
        }
        private void btnDelteAnSkill_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                foreach (Skill tem in theShower.KillMonData.TheSkills) {
                    if (tem.ToString() == cmbAnSkills.Text) {
                        theShower.KillMonData.TheSkills.Remove(tem);
                        cmbAnSkills.Items.Remove(cmbAnSkills.SelectedItem);
                        theShower.KillMonData.Save();
                        cmbAnSkills.Text = "";
                        break;
                    }
                }
            }
        }

        #endregion

        #region 局域网答题

        /// <summary>
        /// 局域网答题开关按钮事件
        /// </summary>
        /// <param name="sender">btnRmoteDati</param>
        /// <param name="e">null</param>
        private void btnRmoteDati_Click(object sender, EventArgs e) {
            //局域网答题开关
            if (DatiManager.LocalDati) {
                txtSeverIP.Enabled = true;
                DatiManager.LocalDati = false;
                DatiManager.LocalDatiService = null;
                btnRmoteDati.Text = "开启答题";
            }
            else {
                var t = new LocalDati();
                if (t.IsReady) {
                    btnRmoteDati.Text = "停止答题";
                    DatiManager.LocalDatiService = t;
                    DatiManager.LocalDati = true;
                    txtSeverIP.Enabled = false;
                }
                else {
                    MsgListener.MsgBoxMsgShow("请检查服务器所在计算IP是否正确", "答题器启动异常");
                }
            }
        }

        #endregion

        #region 自定义提示音乐
        internal static Config<string> AlarmMusicFile = new Config<string>("./common.cfg", "AlarmMusic/FileNmae", "./alarm.mp3");
        private void btnSetAlarmMusic_Click(object sender, EventArgs e) {
            var dia = new OpenFileDialog { Filter = @"音乐文件(*.MP3)|*.MP3" };
            if (dia.ShowDialog(this) == DialogResult.OK) {
                AlarmMusicFile.Value = dia.FileName;
                this.lbAlarmMusic.Text = AlarmMusicFile.Value;
            }
        }
        #endregion

        #region 答题充值
        private void frmPayUrl_Click(object sender, EventArgs e) {
            ShowDatiPage();
        }

        private void ShowDatiPage() {
            var url = "http://xiaolanchong.duapp.com";
            try {
                Process.Start(url);
            }
            catch {
                try { Process.Start("Chrome.exe", url); }
                catch { Process.Start("iexplore.exe", url); }
            }
        }
        #endregion

        #region 收取元宝

        /// <summary>
        /// 元宝收取的比例
        /// </summary>
        internal static Config<double> YuanBaoBiLi = new Config<double>("./common.cfg", "YuanBao/BiLi", 1);

        /// <summary>
        /// 设置元宝比列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetYuanBaoBili_Click(object sender, EventArgs e) {
            int i;
            if (int.TryParse(txtYuanBaoBiLi.Text, out i)) {
                double per = (double)i / 1000;
                string msg = string.Format("请问是否将元宝收购比例设置为{0},表示使用{1}收购1000YB.\r\n是更改比例，否取消本次更改,保持比例{2}", per.ToString("0.00"), i, YuanBaoBiLi.Value);
                if (MessageBox.Show(this, msg, @"更改提示", MessageBoxButtons.OKCancel) == DialogResult.OK) {
                    YuanBaoBiLi.Value = per;
                }
            }
            else {
                CommonMsgEvent("比例设置失败！");
            }
        }
        #endregion

        #region 种植配置

        /// <summary>
        /// 种植地图选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbZzMap_SelectedIndexChanged(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                var comboBox = sender as ComboBox;
                if (comboBox != null) {
                    theShower.TheZhongZhiInfo.DefaultZhongZhiMap = comboBox.Text;
                    theShower.SaveZhongZhiConfig();
                }
            }
        }

        /// <summary>
        /// 种植作物设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbZzZuoWu_SelectedIndexChanged(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                var comboBox = sender as ComboBox;
                if (comboBox != null) {
                    theShower.TheZhongZhiInfo.DefaultZhongZhiZuoWu = comboBox.Text.Trim();
                    theShower.SaveZhongZhiConfig();
                }
            }
        }

        /// <summary>
        /// 种植熟制设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbZzShuZhi_SelectedIndexChanged(object sender, EventArgs e) {
            var comboBox = sender as ComboBox;
            if (comboBox != null) {
                if (Enum.TryParse(comboBox.Text, out theShower.TheZhongZhiInfo.DefaultZhongZhiShuZhi))
                    theShower.SaveZhongZhiConfig();
            }
        }

        /// <summary>
        /// 早产转晚产设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxZzZhuanZhong_CheckedChanged(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                var checkBox = sender as CheckBox;
                if (checkBox != null) {
                    theShower.TheZhongZhiInfo.AutoChangetZaoToWan = checkBox.Checked;
                    theShower.SaveZhongZhiConfig();
                }
            }
        }


        /// <summary>
        /// 早产转晚产的精力
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtZzEnergy_TextChanged(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                var textBox = sender as TextBox;
                if (textBox != null) {
                    if (int.TryParse(textBox.Text.Trim(), out theShower.TheZhongZhiInfo.LowestEnergy))
                        theShower.SaveZhongZhiConfig();
                }
            }
        }

        #endregion

        #region 日志处理
        private void btnStartPlant_Click(object sender, EventArgs e) {
            if (TheShowerCheck() && !theShower.Controler.ZZControler) {
                theShower.TaskStartManger(ThreadMethods.种植);
            }
        }

        private void ClearLog_Click(object sender, EventArgs e) {
            lsDialog.Items.Clear();
        }

        private void SaveLog_Click(object sender, EventArgs e) {
            string path = @".\user\运行日志\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            string fileName = string.Format(@"{1}{0}.log", DateTime.Now.Date.ToString("yy-MM-dd"), path);
            var log = new StringBuilder("************************************************************\r\n");
            foreach (var str in lsDialog.Items) {
                log.AppendFormat("{0}\r\n", str);
            }
            File.AppendAllText(fileName, log.ToString());
        }

        #endregion

        #region 自动喊话
        private void btnBunking_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                if (theShower.Controler.BunkingControler) {
                    theShower.Controler.BunkingControler = false;
                }
                else {
                    DirectDealGame.BunkingAdd(theShower);
                }
                btnBunking.Text = theShower.Controler.BunkingControler ? "停止喊话" : "开始喊话";
            }
        }
        #endregion

        #region 自动登陆相关

        private void InsertAccount(object sender, EventArgs e) {
            var acc = new Account();
            acc.username = txtAccUserName.Text.Trim();
            acc.password = txtAccPassword.Text.Trim();
            acc.serverArea = txtAccServerArea.Text.Trim();
            acc.serverName = txtAccServerName.Text.Trim();
            acc.shouldCheck = true;
            if (Manager.AccMgr.InsertAccount(acc))
                ShowList();
        }

        /// <summary>
        /// 重新加载账号显示控件信息
        /// </summary>
        private void ShowList() {
            AccList.Items.Clear();
            foreach (var acc in Manager.AccMgr.Accounts) {
                var item = AccList.Items.Add(acc.username);
                item.SubItems.Add(acc.charaterName);
                item.SubItems.Add(acc.serverArea);
                item.SubItems.Add(acc.serverName);
            }
        }


        /// <summary>
        /// 删除账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeletAccount_Click(object sender, EventArgs e) {
            if (AccList.SelectedItems.Count > 0) {
                var item = AccList.SelectedItems[0];
                var userName = item.SubItems[0].Text;
                var ask = MessageBox.Show(this, "是否执行登陆账号：\r\n" + userName, "删除账号", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (ask == DialogResult.Yes) {
                    Manager.AccMgr.DeleteAccout(userName);
                    AccList.Items.Remove(item);
                }
            }
        }

        /// <summary>
        /// 设置游戏路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetGamePath_Click(object sender, EventArgs e) {
            var dia = new FolderBrowserDialog();
            if (dia.ShowDialog(this) == DialogResult.OK) {
                txtGamePath.Text = dia.SelectedPath;
            }
        }


        /// <summary>
        /// 自带多开器打开游戏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartGame_Click(object sender, EventArgs e) {
            Manager.AccMgr.StartGame();
        }

        /// <summary>
        /// 开启自动登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoLogin_Click(object sender, EventArgs e) {
            var acc = GetAccountBySelectedItem();
            if (acc != null) {
                var ask = MessageBox.Show(this, "是否执行登陆账号：\r\n" + acc.username, "登陆提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (ask == DialogResult.Yes)
                    Manager.AccMgr.Login(acc);
            }
        }

        /// <summary>
        /// 启动本地答题服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLocalDatiSever_Click(object sender, EventArgs e) {
            Process.Start(Path.Combine(Application.StartupPath, "Server.exe"));
        }

        #endregion

        #region 密保卡
        /// <summary>
        /// 设置密保卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetMibaoka(object sender, EventArgs e) {
            var acc = GetAccountBySelectedItem();
            if (acc == null)
                return;

            using (var dia = new OpenFileDialog()) {
                dia.Filter = "JPEG|*.JPG|BMP|*bmp";
                var dr = dia.ShowDialog();
                if (dr == DialogResult.OK) {
                    var fileName = dia.FileName;
                    var card = Password.AutoRecoginze.RecoginzeFromImage(fileName);
                    if (acc.SetMibaoka(card.SerialId)) {
                        Password.SecretCardDAL.SaveSecretCard(card);
                        MsgListener.MsgBoxMsgShow(string.Format("{0}已经绑定密保卡！", acc.username), "密保提示");
                    }
                }
            }
        }

        /// <summary>
        /// 去除密保卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemoveMibaoka(object sender, EventArgs e) {
            var acc = GetAccountBySelectedItem();
            if (acc.SetMibaoka("")) {
                MsgListener.MsgBoxMsgShow(string.Format("{0}的密保卡信息已经清除了！", acc.username), "密保提示");
            }
        }

        /// <summary>
        /// 查看密保卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowAccPasswordMsgBox(object sender, EventArgs e) {
            var acc = GetAccountBySelectedItem();
            if (acc != null)
                MsgListener.MsgBoxMsgShow(acc.password, "密码查看");
        }

        /// <summary>
        /// 通过选中项的信息来获取账号信息
        /// </summary>
        /// <returns></returns>
        private Account GetAccountBySelectedItem() {
            Account acc = null;
            if (AccList.SelectedItems.Count > 0) {
                var item = AccList.SelectedItems[0];
                var userName = item.SubItems[0].Text;
                acc = Manager.AccMgr.GetAccountByUserName(userName);
            }
            return acc;
        }

        /// <summary>
        /// 查询密保信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckMibao(object sender, EventArgs e) {
            var acc = GetAccountBySelectedItem();
            if (acc != null) {
                var mbId = acc.mbId;

                var result = !string.IsNullOrEmpty(mbId)
                    ? string.Format("已经绑定了密保卡\r\n密保序列号为: \r\n\t{0}", mbId)
                    : "未绑定密保卡";

                MsgListener.MsgBoxMsgShow(string.Format("{0}的{1}！", acc.username, result), "密保提示");
            }
        }
        #endregion

        #region 自动摆摊系统
        private void RefreshShowAccList(object sender, EventArgs e) {
            ShowList();
        }

        private void AddSellMap(string name, string price) {
            Int32 p;
            if (Int32.TryParse(price, out p)) {
                if (TheShowerCheck()) {
                    theShower.BaitanConf.SetPrice(name, p.ToString());
                }
            }
        }


        private void btnBaitanDingwei_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                theShower.SetBaitanLocation();
                lbBaitanLocation.Text = theShower.BaitanConf.ShowMapAndLocation();
            }
        }

        private void btnAddBaitanSails_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                AddSellMap(cbxBaitanName.Text, cbxBaitanPrice.Text);
                ShowBaitanPriceMap();
            }
        }

        private void ShowBaitanPriceMap() {
            if (TheShowerCheck()) {
                cbxBaitanPriceShow.Items.Clear();
                cbxBaitanPriceShow.Items.AddRange(theShower.BaitanConf.ShowPriceMap().ToArray());
            }
        }
        #endregion

        /// <summary>
        /// 摆摊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e) {
            StartWork(ThreadMethods.摆摊);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e) {
            StopWorking(sender, e);
            StartWork(ThreadMethods.收摊);
        }

        private void btnBaoPen_Click(object sender, EventArgs e) {
            StartWork(ThreadMethods.帮会宝盆);
        }

        private void btnLoulanHuanJin_Click(object sender, EventArgs e) {
            StartWork(ThreadMethods.楼兰幻境);
        }

        private void button4_Click(object sender, EventArgs e) {
            if (TheShowerCheck()) {
                new Task(theShower.TestMethod).Start();
            }
        }
    }
}
